﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using CygwinPackageManager.Common.Properties;
using System.Runtime.CompilerServices;

namespace CygwinPackageManager.Common
{
	public class InstalledPackageDALC : PackageBaseDALC
	{
		

		private static IEnumerable<InstalledPackage> _installedPackages;
		public static IEnumerable<InstalledPackage> InstalledPackages
		{
			[MethodImpl(MethodImplOptions.Synchronized)]
			get
			{
				if (_installedPackages == null)
					_installedPackages = _GetInstalledPackages();
				return _installedPackages;
			}
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		private static IEnumerable<InstalledPackage> _GetInstalledPackages()
		{
			InstallationInfo installation = InstallationManager.GetInstallationInfo();

			if (!installation.IsReady)
				throw new InvalidOperationException("Cygwin not ready.");

			string installedContent = string.Empty;
			try
			{
				installedContent = File.ReadAllText(Utils.GetInstalledPackagesDBPath(installation.RootDirectory));
			}
			catch (Exception ex)
			{
				throw new Exception("Cannot read installed content.", ex);
			}

			List<InstalledPackage> packages = new List<InstalledPackage>();
			foreach (Match packageMatch in Regex.Matches(installedContent, Resources.InstalledPackagesRegex, RegexOptions.Multiline))
			{
				string packageName = packageMatch.Groups["Name"].Value.ExtendedTrim();
				packages.Add(new InstalledPackage()
				{
					// Extended base information.
					PackageID = GetPackageID(packageName),

					// Base information.
					IsSpecial = packageName.StartsWith("_"),
					Name = packageName,
					ReleaseVersion = packageMatch.Groups["Release"].Value.ExtendedTrim(),
					VendorVersion = packageMatch.Groups["Version"].Value.ExtendedTrim(),
				});
			}

			return packages;
		}

		public IEnumerable<InstalledPackage> GetInstalledPackages()
		{
			return InstalledPackages;
		}
	}
}
